<template>
  <div class="selectInput">
    <!-- {{value}} -->
    <el-form :model="formData" ref="formData">
      <el-form-item prop="param">
        <ConditionsType v-model="formData.param" @change="valueChange" ref="conditionsType"></ConditionsType>
      </el-form-item>
      <!-- 函数类型不需要显示 -->
      <div class="flex" v-if="type !== '1'">
        <div class="mr-5 fontMini">"当前选项"</div>
        <el-form-item prop="currentValue" class="flex1" :rules="rules.currentValue">
          <el-select class="flex1" size="mini" v-model="formData.currentValue" clearable multiple @change="valueChange">
            <el-option v-for="item in optionsList" :key="item.value" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <div class="ml-5 fontMini">显示</div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import ConditionsType from './conditionsType'
export default {
  name: 'selectInput',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: Object
  },
  components: {
    // CodeMirrorJs,
    ConditionsType
  },
  data() {
    return {
      formData: this.formDataInit(),
      rules: {
        currentValue: [
          {required: true, message: '当前选项不能为空', trigger: 'change'}
        ]
      }
    }
  },
  computed: {
    ...mapState('pageData', ['activeFormData']),
    optionsList() {
      const { optionsSource, options, urlData } = this.activeFormData
      return optionsSource === '0' ? options : urlData?.urlOptions
    },
    type() {
      return this.value?.param?.type
    }
  },
  watch: {
    value: {
      handler(val) {
        this.formData = JSON.stringify(val) === '{}' ? this.formDataInit() : val
        // if (JSON.stringify(val) === '{}') {
        //   this.currentValue = []
        //   this.param = {}
        // } else {
        //   const { currentValue, ...query } = val
        //   this.currentValue = currentValue
        //   this.param = query
        // }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    formDataInit() {
      return {
        currentValue: [],
        param: {}
      }
    },
    valueChange() {
      this.$emit('change', this.formData)
    },
    // 校验子组件是否成功和当前form是否成功
    verfiyForm() {
      return new Promise(async resovle => {
        const res = await this.$refs.conditionsType.verfiyForm()
        this.$refs.formData.validate(valid => {
          if (valid && res === 'success') {
            resovle('success')
          } else {
            resovle('error')
          }
        })
      })
    }
  }
}
</script>